<template>
  <rt-view>
    <rt-header>
      <rt-list-header>
        <rt-header-icon slot="icon" icon="rt-base-default" />
        <rt-header-title :title="viewTitle" />
        <div slot="btn">
          <rt-button icon-name="rt-base-save" type="primary" @click="save()">
            {{ !isUpdate ? '提交' : '保存' }}
          </rt-button>
          <rt-button icon-name="rt-base-back" @click="back()">返回</rt-button>
        </div>
      </rt-list-header>
    </rt-header>
    <rt-content>
      <rt-card>
        <rt-section>
          <rt-form ref="editForm" :model="infoData" :rules="rules">
            <rt-row :gutter="15">
              <div v-for="(item, index) in items" :key="index">
                <rt-col :span="item.single ? 24 : 7">
                  <rt-form-item
                    :label="item.label"
                    :required="item.required"
                    :prop="item.prop"
                  >
                    <rt-picklist
                      v-if="item.type == 'picklist'"
                      v-model="infoData[item.prop]"
                      :fetch="fetchPickList(item.data)"
                    />
                    <rt-input v-else v-model="infoData[item.prop]" />
                  </rt-form-item>
                </rt-col>
              </div>
            </rt-row>
          </rt-form>
        </rt-section>
      </rt-card>
    </rt-content>
  </rt-view>
</template>
<script>
import { mapState } from 'vuex';
export default {
  props: {
    items: {
      type: [Array, Object],
      required: true
    },
    title: {
      type: String
    },
    controllerName: {
      type: String,
      required: true
    },
    //表名
    tableName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      isUpdate:
        this.$route.params.id != null && this.$route.params.id != undefined,
      id:
        this.$route.params.id != null && this.$route.params.id != undefined
          ? this.$route.params.id
          : '',
      oldData: {},
      infoData: {}
    };
  },
  computed: {
    viewTitle() {
      return this.title;
    },
    rules() {
      let rule = {};
      this.items.forEach(e => {
        if (e.required) {
          rule[e.prop] = [
            {
              required: true,
              message: `${e.label}为必填项`,
              trigger: 'blur'
            }
          ];
        }
      });
      return rule;
    }
  },
  mounted() {
    // this.loadData("");
  },
  created() {
    this.initInfoData();
    if (this.isUpdate) {
      this.loadData();
    }
  },
  methods: {
    initInfoData() {
      let that = this;
      this.items.forEach(e => {
        this.$set(this.infoData, e.prop, '');
      });
    },
    async loadData() {
      rt.get(`api/${this.controllerName}/detail/${this.id}`)
        .then(res => {
          this.infoData = res;
          this.oldData = JSON.stringify(res);
          this.checkData();
        })
        .catch(error => {
          rt.showErrorToast(error);
        });
    },
    save() {
      if (this.isUpdate) {
        let value = JSON.stringify(this.infoData);
        if (value === this.oldData) {
          rt.showErrorToast('数据未发生改变！');
          return;
        }
      }
      let operate = this.isUpdate ? 'update' : 'create';
      this.$refs.editForm.$children[0].validate(valid => {
        if (valid) {
          rt.post(`api/${this.controllerName}/${operate}`, this.checkData())
            .then(res => {
              this.back();
            })
            .catch(error => {
              rt.showErrorToast(error);
            });
        } else {
          return false;
        }
      });
    },
    back() {
      this.$router.back();
    },
    /**
     * 比较列属性和获取详情中的属性对比，返回要编辑的数据
     */
    checkData() {
      let editData = {};
      this.items.forEach(e => {
        editData[e.prop] = this.infoData[e.prop];
      });
      editData[`${this.tableName}id`] = this.infoData[`${this.tableName}id`];
      return editData;
    },
    fetchPickList(data) {
      console.log(data);
      // return new Promise(resolve => {
      //   setTimeout(() => {
      //     resolve(data);
      //   }, 10);
      // });
    }
  }
};
</script>
<style></style>
